package com.jt.util;

import sun.awt.SunHints;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    /**
     * 该工具api主要任务:
     *  1.根据cookie名称返回对象
     *  2.根据cookie名称返回值
     *  3.新增cookie方法
     *  4.删除cookie方法
     */
    public static Cookie getCookie(String name,HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {
                if (name.equalsIgnoreCase(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static String getValue(String name,HttpServletRequest request){
        Cookie cookie = getCookie(name,request);
        return cookie==null?null:cookie.getValue();
    }


    public static void addCookie(String name, String value,String path,String domain,int maxAge,HttpServletResponse response){
        Cookie cookie = new Cookie(name,value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public static void deleteCookie(String name,String path,String domain,HttpServletResponse response){
        addCookie(name,"",path,domain,0,response);
    }
}
